<template>
  <view class="add-friend-container">
    <!-- 头部 -->
    <view class="header">
      <view class="back-btn" @click="goBack">
        <text class="back-icon">‹</text>
      </view>
      <text class="header-title">添加好友</text>
      <view class="placeholder"></view>
    </view>

    <!-- 搜索区域 -->
    <view class="search-section">
      <view class="search-container">
        <view class="search-box">
          <text class="search-icon">🔍</text>
          <input 
            class="search-input" 
            type="text" 
            placeholder="输入邮箱地址搜索" 
            v-model="searchKeyword"
            @input="onSearchInput"
            @confirm="searchUsers"
          />
        </view>
        <view class="search-btn" @click="searchUsers">
          <text class="search-btn-text">搜索</text>
        </view>
      </view>
    </view>

    <!-- 搜索结果 -->
    <view class="search-results" v-if="searchResults.length > 0">
      <view class="result-header">
        <text class="result-title">搜索结果</text>
        <text class="result-count">共{{ searchResults.length }}个结果</text>
      </view>
      
      <view class="user-list">
        <view 
          class="user-item" 
          v-for="user in searchResults" 
          :key="user.id"
          @click="showUserDetail(user)"
        >
          <view class="user-avatar">
            <image class="avatar" :src="user.avatar || '/static/logo.png'" mode="aspectFill" />
            <view class="online-status" v-if="user.status === 'online'" :style="{ backgroundColor: getUserStatusColor(user.status) }"></view>
          </view>
          <view class="user-info">
            <text class="user-name">{{ user.nickName || user.username }}</text>
            <text class="user-status">{{ getUserStatusText(user.status) }}</text>
          </view>
          <view class="action-btn" @click.stop="sendFriendRequest(user)" :class="{ 'disabled': user.isFriend || user.requestSent }">
            <text class="btn-text">
              {{ user.isFriend ? '已是好友' : (user.requestSent ? '已发送' : '添加') }}
            </text>
          </view>
        </view>
      </view>
    </view>

    <!-- 空状态 -->
    <view class="empty-state" v-else-if="hasSearched && searchResults.length === 0">
      <text class="empty-icon">🔍</text>
      <text class="empty-text">未找到相关用户</text>
      <text class="empty-hint">请尝试其他关键词</text>
    </view>

    <!-- 默认状态 -->
    <view class="default-state" v-else>
      <text class="default-icon">👥</text>
      <text class="default-text">搜索用户添加好友</text>
      <text class="default-hint">输入邮箱地址进行搜索</text>
    </view>

    <!-- 加载状态 -->
    <view class="loading-state" v-if="loading">
      <text class="loading-text">搜索中...</text>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { AuthUtils, getUserStatusText, getUserStatusColor } from '@/utils/auth'
import { ContactAPI } from '@/utils/api'

// 搜索相关
const searchKeyword = ref('')
const searchResults = ref<any[]>([])
const loading = ref(false)
const hasSearched = ref(false)

// 页面加载时检查登录状态
onMounted(() => {
  if (!AuthUtils.isLoggedIn()) {
    uni.showToast({
      title: '请先登录',
      icon: 'none'
    })
    setTimeout(() => {
      uni.reLaunch({
        url: '/pages/login'
      })
    }, 1500)
  }
})

// 返回上一页
const goBack = () => {
  uni.switchTab({
    url: '/pages/message'
  })
}

// 搜索输入处理
const onSearchInput = (e: any) => {
  searchKeyword.value = e.detail.value
}

// 搜索用户
const searchUsers = async () => {
  if (!searchKeyword.value.trim()) {
    uni.showToast({
      title: '请输入搜索关键词',
      icon: 'none'
    })
    return
  }

  // 验证邮箱格式
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  if (!emailRegex.test(searchKeyword.value)) {
    uni.showToast({
      title: '请输入正确的邮箱格式',
      icon: 'none'
    })
    return
  }

  loading.value = true
  hasSearched.value = true
  
  try {
    const response = await ContactAPI.searchUsers(searchKeyword.value)
    
    if (response.code === 200 && response.data?.user) {
      // 找到用户，转换数据格式
      const user = response.data.user
      searchResults.value = [{
        id: user.userId,
        username: user.email,
        nickName: user.nickName,
        avatar: user.avatar || '/static/logo.png',
        status: user.status === 1 ? 'online' : 'offline',
        isFriend: user.isFriend
      }]
    } else {
      // 未找到用户
      searchResults.value = []
    }
    
  } catch (error: any) {
    console.error('搜索用户失败:', error)
    searchResults.value = []
    
    // 根据错误信息显示不同的提示
    if (error.message?.includes('未找到')) {
      uni.showToast({
        title: '未找到该用户',
        icon: 'none'
      })
    } else if (error.message?.includes('邮箱')) {
      uni.showToast({
        title: '邮箱格式不正确',
        icon: 'none'
      })
    } else {
      uni.showToast({
        title: '搜索失败，请重试',
        icon: 'none'
      })
    }
  } finally {
    loading.value = false
  }
}

// 显示用户详情
const showUserDetail = (user: any) => {
  console.log('查看用户详情:', user)
  // 这里可以跳转到用户详情页面
}

// 发送好友申请
const sendFriendRequest = async (user: any) => {
  if (user.isFriend) {
    uni.showToast({
      title: '已经是好友了',
      icon: 'none'
    })
    return
  }

  if (user.requestSent) {
    uni.showToast({
      title: '好友申请已发送',
      icon: 'none'
    })
    return
  }

  uni.showModal({
    title: '添加好友',
    content: `确定要向 ${user.nickName || user.username} 发送好友申请吗？`,
    success: async (res) => {
      if (res.confirm) {
        try {
          // 显示加载提示
          uni.showLoading({
            title: '发送中...'
          })
          
          // 调用发送好友申请的API
          const response = await ContactAPI.sendFriendRequest(user.username, '希望能成为好友')
          
          uni.hideLoading()
          
          if (response.code === 200) {
            uni.showToast({
              title: '好友申请已发送',
              icon: 'success'
            })
            
            // 更新用户状态
            const userIndex = searchResults.value.findIndex(u => u.id === user.id)
            if (userIndex !== -1) {
              searchResults.value[userIndex].requestSent = true
            }
          } else {
            throw new Error(response.message || '发送失败')
          }
        } catch (error: any) {
          uni.hideLoading()
          console.error('发送好友申请失败:', error)
          
          // 根据错误信息显示不同的提示
          if (error.message?.includes('已经是好友')) {
            uni.showToast({
              title: '你们已经是好友了',
              icon: 'none'
            })
          } else if (error.message?.includes('已发送')) {
            uni.showToast({
              title: '好友申请已发送过',
              icon: 'none'
            })
          } else if (error.message?.includes('不能添加自己')) {
            uni.showToast({
              title: '不能添加自己为好友',
              icon: 'none'
            })
          } else {
            uni.showToast({
              title: error.message || '发送失败，请重试',
              icon: 'none'
            })
          }
        }
      }
    }
  })
}
</script>

<style scoped>
.add-friend-container {
  height: 100vh;
  background-color: #f8f9fa;
  display: flex;
  flex-direction: column;
}

/* 头部 */
.header {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  background-color: #ffffff;
  padding: 30rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-bottom: 1rpx solid #e5e5e5;
  z-index: 100;
}

.back-btn {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.back-icon {
  font-size: 48rpx;
  color: #007AFF;
  font-weight: bold;
}

.header-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333333;
}

.placeholder {
  width: 60rpx;
}

/* 搜索区域 */
.search-section {
  margin-top: 120rpx;
  padding: 30rpx;
  background-color: #ffffff;
  border-bottom: 1rpx solid #e5e5e5;
}

.search-container {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.search-box {
  flex: 1;
  display: flex;
  align-items: center;
  background-color: #f5f5f5;
  border-radius: 50rpx;
  padding: 0 30rpx;
  height: 80rpx;
}

.search-icon {
  font-size: 28rpx;
  color: #999999;
  margin-right: 20rpx;
}

.search-input {
  flex: 1;
  font-size: 28rpx;
  color: #333333;
  background: transparent;
  border: none;
  outline: none;
}

.search-btn {
  background-color: #007AFF;
  border-radius: 40rpx;
  padding: 16rpx 32rpx;
  flex-shrink: 0;
}

.search-btn-text {
  font-size: 24rpx;
  color: #ffffff;
  font-weight: 500;
}

/* 搜索结果 */
.search-results {
  flex: 1;
  background-color: #ffffff;
  margin-top: 20rpx;
}

.result-header {
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.result-title {
  font-size: 28rpx;
  font-weight: 500;
  color: #333333;
}

.result-count {
  font-size: 24rpx;
  color: #999999;
}

.user-list {
  padding: 0 30rpx;
}

.user-item {
  display: flex;
  align-items: center;
  padding: 30rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
  transition: background-color 0.2s;
}

.user-item:last-child {
  border-bottom: none;
}

.user-item:active {
  background-color: #f8f9fa;
}

.user-avatar {
  position: relative;
  margin-right: 24rpx;
}

.user-avatar .avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 40rpx;
}

.online-status {
  position: absolute;
  bottom: 4rpx;
  right: 4rpx;
  width: 20rpx;
  height: 20rpx;
  background-color: #52c41a;
  border-radius: 50%;
  border: 3rpx solid #ffffff;
}

.user-info {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.user-name {
  font-size: 28rpx;
  font-weight: 500;
  color: #333333;
  margin-bottom: 8rpx;
}

.user-status {
  font-size: 24rpx;
  color: #999999;
}

.action-btn {
  background-color: #007AFF;
  border-radius: 40rpx;
  padding: 16rpx 32rpx;
  transition: all 0.3s ease;
}

.action-btn:active {
  transform: scale(0.95);
  background-color: #0056CC;
}

.action-btn.disabled {
  background-color: #f0f0f0;
  pointer-events: none;
}

.action-btn.disabled .btn-text {
  color: #999999;
}

.btn-text {
  font-size: 24rpx;
  color: #ffffff;
  font-weight: 500;
}

/* 状态页面 */
.empty-state,
.default-state {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 60rpx;
}

.empty-icon,
.default-icon {
  font-size: 120rpx;
  margin-bottom: 40rpx;
}

.empty-text,
.default-text {
  font-size: 32rpx;
  color: #333333;
  font-weight: 500;
  margin-bottom: 16rpx;
}

.empty-hint,
.default-hint {
  font-size: 26rpx;
  color: #999999;
  text-align: center;
  line-height: 1.5;
}

.loading-state {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: rgba(0, 0, 0, 0.7);
  color: #ffffff;
  padding: 30rpx 60rpx;
  border-radius: 20rpx;
  z-index: 1000;
}

.loading-text {
  font-size: 28rpx;
  color: #ffffff;
}
</style>